package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.weibo.pojo.vo.WeiboIndexVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
public class WeiboController {

    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/weibo/insert")
    public int insert(@RequestBody WeiboDto weibo, HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return 2;
        }

        System.out.println("weibo = " + weibo);

        Weibo w = new Weibo();
        BeanUtils.copyProperties(weibo, w);
        w.setCreated(new Date());
        w.setUserId(user.getId());

        mapper.insert(w);
        return 1;

    }

    @RequestMapping("/weibo/select")
    public List<WeiboIndexVO> select() {


        return mapper.select();
    }

    @RequestMapping("/weibo/selectById")
    public WeiboDetailVO selectById(int id) {
        //当return的内容为自定义对象或List集合时,SpringMVC框架会自动将其转成
        //JSON格式的字符串 再通过网络传输出去.

        return mapper.selectById(id);
    }
}
